package cn.kgc.crowdfundingadminspringboot2.controller;

import cn.kgc.crowdfundingadminspringboot2.common.ResultEntity;
import cn.kgc.crowdfundingadminspringboot2.pojo.Tag;
import cn.kgc.crowdfundingadminspringboot2.service.TagService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/tag")
public class TagController {
    @Resource
    TagService tagService;
    @RequestMapping("/to/page.html")
    public String tag(){
        return "/tag-page";
    }


    @RequestMapping("/get/whole/tree")
    @ResponseBody
    public ResultEntity<Tag> getAll(){
        List<Tag> all = tagService.getAll();
        Map<Integer,Tag> tagMap=new HashMap<>();
        for (Tag tag : all) {
            tagMap.put(tag.getId(),tag);
        }
        // 3.声明变量用于存储根节点对象
        Tag rootNode = null;

        for (Tag tag : all) {
            //是父节点
            if (tag.getPid()==null){
                rootNode=tag;
                continue;
            }
            //是子节点从tagMap找到父节点，并添加到父节点的子节点集合中
            tagMap.get(tag.getPid()).getChildren().add(tag);
        }
        return ResultEntity.successWithoutData(rootNode);
}
    @RequestMapping("/save")
    @ResponseBody
    public ResultEntity<String> savetag(Tag tag) {

        tagService.savetag(tag);

        return ResultEntity.successWithoutData();
    }


    @RequestMapping("/get/{tagId}")
    @ResponseBody
    public ResultEntity<Tag> gettagById(@PathVariable("tagId") Integer tagId) {

        Tag tag = tagService.gettagById(tagId);

        return ResultEntity.successWithoutData(tag);
    }

    @ResponseBody
    @RequestMapping("/batch/remove")
    public ResultEntity<String> batchRemove(@RequestBody List<Integer> tagList){
       tagService.batchRemove(tagList);
        return ResultEntity.successWithoutData();
    }


    @RequestMapping("/update")
    @ResponseBody
    public ResultEntity<String> update(Tag tag){
       tagService.update(tag);
        return ResultEntity.successWithoutData();
    }
}
